/*!
 * superbly tagfield v0.1
 * http://www.superbly.ch
 *
 * Copyright 2011, Manuel Spierenburg
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.superbly.ch/licenses/mit-license.txt
 * http://www.superbly.ch/licenses/gpl-2.0.txt
 *
 * Date: Sun Mar 6 13:55:29 2011 -0500
 */
function superblyTagField(tagField,url,preset,allowNewTags,showTagsNumber, loadingPath, isFixData, addCallBack, removeCallBack, strInputDefault, indexWhenCallAddCallBack, widthInput)
{
	addCallBack = (typeof(addCallBack) === 'undefined' || addCallBack === '') ? null : addCallBack;
	removeCallBack = (typeof(removeCallBack) === 'undefined' || removeCallBack === '') ? null : removeCallBack;
	strInputDefault = (typeof(strInputDefault) === 'undefined' || strInputDefault === '') ? '' : strInputDefault;
	indexWhenCallAddCallBack = (typeof(indexWhenCallAddCallBack) === 'undefined' || indexWhenCallAddCallBack === '') ? -1 : indexWhenCallAddCallBack;
	widthInput = (typeof(widthInput) === 'undefined' || widthInput === '') ? '350' : widthInput;
	var tags = new Array();
	var tagstmp = tags.slice();
	if(isFixData)
	{
		var _onError = function()
		{
			return;
		}
		var _onSuccess = function(data)
		{
			tags = jQuery.parseJSON(data);
			tagstmp = tags.slice();
			// set presets
			var check = false;
			for(i in preset)
			{
				check = (indexWhenCallAddCallBack == -1) ? true : ((i == indexWhenCallAddCallBack) ? true : false);
				addItem(preset[i], check);
			}
		};
		$.ajax({
			url: url,
			success: _onSuccess,
			error: _onError
	 	});
 	}
	
	// prepare needed vars
	var inserted = new Array();
	var selectedIndex = null;
	var currentValue = null;
	var currentItem = null;
	var hoverSuggestItems = false;
	
	tagField.wrap('<li class="superblyTagInputItem" />');
	tagField.after('<ul class="superblySuggestItems" />');
	
	if(strInputDefault == '')
	{
		tagField.after('<input class="superblyTagInput" type="text" autocomplete="false" style="width: 0px;" />');
	}
	else
	{
		if(preset == '')
		{
			tagField.after('<input class="superblyTagInput" type="text" autocomplete="false" value="' + strInputDefault + '" style="width: ' + widthInput + 'px;" />');
		}
		else
		{
			tagField.after('<input class="superblyTagInput" type="text" autocomplete="false" style="width: 0px;" />');
		}
	}
	tagField.parent('.superblyTagInputItem').wrap('<ul class="superblyTagItems" />');
	tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').wrap('<div class="superblyTagfieldDiv" />');
	tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').parent('.superblyTagfieldDiv').append('<img class="superblyTagfieldLoading" src="' + loadingPath +  '"/>');
	tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').parent('.superblyTagfieldDiv').append('<div class="superblyTagfieldClearer" />');
		
	// events
	tagField.siblings('.superblySuggestItems').mouseover(function(e){
   		hoverSuggestItems = true;
   	});
   	
   	tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').mouseleave(function(e){
   		hoverSuggestItems = false; 
   	});
	
	tagField.siblings('.superblyTagInput').keyup(function(e){
   		
		if( e.keyCode!= 40 &&  e.keyCode != 38 && ((e.keyCode >= 33 && e.keyCode <= 126 ) || e.keyCode == 8))
		{
			tagField.siblings('.superblyTagInput').parent('.superblyTagInputItem').parent('.superblyTagItems').parent('.superblyTagfieldDiv').children('.superblyTagfieldLoading').show();
			if($.trim($(this).val()) != '')
			{
				if(!isFixData)
				{
					var obj = this;
					var keyword = $.trim($(obj).val());
					var params = 'keyword=' + url_encode(keyword);
					var _onError = function()
					{
						return;
					}
					var _onSuccess = function(data)
					{
						tags = jQuery.parseJSON(data);
						tagstmp = tags.slice();
						suggest($(obj).val());
					};
					$.ajax({
						url: url,
						success: _onSuccess,
						error: _onError,
						data: params
				 	});
			 	}
			 	else
			 	{
			 		suggest($(this).val());
			 	}
		 	}
		 	else
		 	{
		 		suggest($(this).val());
		 	}
		}
		else if(e.keyCode == 13)
		{
			/*
			if($(this).val() == ''){
				tags = new Array();
				tagstmp = tags.slice();
				suggest($(this).val());
				return;
			}*/
			
			if(currentItem != null){
     			addItem(currentItem);
     		} else if(allowNewTags){
     			var value = tagField.siblings('.superblyTagInput').val();
     			if(value != null && value != ''){
     				addItem(value);
     			}
     		}
     	
		}
		else
		{
			if($(this).val() != '')
			{
				suggest($(this).val());
			}
		}
		
   	});
   
   	tagField.siblings('.superblyTagInput').focusout(function(e){
   		if(!hoverSuggestItems){
   			tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').css('display', 'none').removeClass('sugperblySuggestItems-Scroll');
   			if(strInputDefault == '')
   			{
   				tagField.siblings('.superblyTagInput').css({width: '0'});
   				tagField.siblings('.superblyTagInput').val('');
			}
			else
			{
				var arrSelectedTag = tagField.siblings('.superblyTagInput').parent('.superblyTagInputItem').parent('.superblyTagItems').children(".superblyTagItem");
				if(arrSelectedTag.length > 0)
				{
					tagField.siblings('.superblyTagInput').css({width: '0'});
   					tagField.siblings('.superblyTagInput').val('');
					
				}
				else
				{
					tagField.siblings('.superblyTagInput').css({width: widthInput + 'px'});
					tagField.siblings('.superblyTagInput').val(strInputDefault);
				}
			}
   		}
   	});
   	
   	tagField.siblings('.superblyTagInput').focus(function(e){
   		currentValue = null;
			if(strInputDefault == '')
			{
   				tagField.siblings('.superblyTagInput').css({width: '100px'});
			}
			else
			{
				tagField.siblings('.superblyTagInput').css({width: '100px'});
				tagField.siblings('.superblyTagInput').val('');
			}
		
  	});
   	
   	tagField.parent('.superblyTagInputItem').keydown(function(e){
		if(e.keyCode == 40) {		
			// arrow key down
			selectDown();
		}else if(e.keyCode == 38) {
			// arrow key up
			selectUp()
		}else if(e.keyCode == 13) {
			// enter
     		if(currentItem != null){
     			addItem(currentItem);
     		} else if(allowNewTags){
     			var value = tagField.siblings('.superblyTagInput').val();
     			if(value != null && value != ''){
     				addItem(value);
     			}
     		}
          	return false;
		}else if(e.keyCode == 8){
             // backspace
             if(tagField.siblings('.superblyTagInput').val() == ''){
             	removeLastItem();
             }
        }
		
   	});
   	
   	tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').parent('.superblyTagfieldDiv').click(function(e){
		tagField.siblings('.superblyTagInput').focus();	
		return;
   	});
	
	
	
	function url_encode (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	}
 
	// private method for UTF-8 decoding
	function url_decode (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
		return string;
	}
	
	/*
	function removeVietChars(str)
	{
		str = preg_replace(/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/, 'a');
		str = preg_replace(/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/, 'e', str);
		str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', str);
		str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', str);
		str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
		str = preg_replace("/(ỳ|ý|y|ỷ|ỹ)/", 'y', str);
		str = preg_replace("/(đ)/", 'd', str);
		str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', str);
		str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', str);
		str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', str);
		str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', str);
		str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', str);
		str = preg_replace("/(Ỳ|Ý|Y|Ỷ|Ỹ)/", 'Y', str);
		str = preg_replace("/(Đ)/", 'D', str);
		//$str = str_replace(" ", "-", str_replace("&*#39;","",$str));
		return str;
	}*/
	
	function removeVietChars(str) {  
		str= str.toLowerCase();  
		str= str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g,"a");  
		str= str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g,"e");  
		str= str.replace(/ì|í|ị|ỉ|ĩ/g,"i");  
		str= str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g,"o");  
		str= str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g,"u");  
		str= str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g,"y");  
		str= str.replace(/đ/g,"d");
		//str= str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g," "); 
		/* tìm và thay thế các kí tự đặc biệt trong chuỗi sang kí tự - */ 
		//str= str.replace(/-+-/g,"-"); //thay thế 2- thành 1- 
		//str= str.replace(/^\-+|\-+$/g,"");  
		//cắt bỏ ký tự - ở đầu và cuối chuỗi  
		return str;  
	}   
	
	// functions 
	function setValue(){
		//console.info(inserted);
		
		//tagField.val(inserted.join(','));
		var arrInsert = new Array();
		var arrSelectedTag = tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children(".superblyTagItem");
		var num = arrSelectedTag.length;
		for(var i = 0; i < num; i++)
		{
			arrInsert.push($(arrSelectedTag[i]).children('.superblyTagItemHddId').val());
		}
		tagField.val(arrInsert.join(','));
	}
	
	function hightlight(val, str)
	{
		if(val == '' || str == '') return str;
		/*
		var strLower = str.toLowerCase();
		var numLength = strLower.length;
		var keyLower = val.toLowerCase();
		var startTmp = 0;
		var realPos = 0;
		var numKey = val.length;
		var countMatch = 0;
	
		while(startTmp < numLength)
		{
			var index = strLower.indexOf(keyLower, startTmp);
			if(index == -1) break;
			var realPos = (countMatch * 7) + index;
			var strLeft = str.substring(0, realPos);
	
			var strMiddle = str.substr(realPos , numKey);
	
			var strRight = str.substring(realPos  + numKey);
	
			str = strLeft + '<b>' + strMiddle + '</b>' + strRight ;
			
			startTmp = index + val.length;
			countMatch++;
		}
		return str;
		*/
		
		var strLower = removeVietChars(str.toLowerCase());
		//strLower= strLower.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g," ");
		var numLength = strLower.length;
		var keyLower = removeVietChars(val.toLowerCase());
		//keyLower= keyLower.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g," ");
		var numKey = val.length;
		//console.info(strLower);
		var index = strLower.indexOf(keyLower, 0);
		//console.info(keyLower);
		if(index > -1)
		{
			var strLeft = str.substring(0, index);
			var strMiddle = str.substr(index, numKey);
			var strRight = str.substring(index  + numKey);
			str = strLeft + '<b>' + strMiddle + '</b>' + strRight ;
		}
		return str;
	}
	
	function addItem(value, isCallAddCallBack){
		isCallAddCallBack = (typeof(isCallAddCallBack) === 'undefined' || isCallAddCallBack === '') ? true : isCallAddCallBack;
		//var index = jQuery.inArray(value,tagstmp);
		var index = -1;
		var numSuggestValue = tagstmp.length;
		for(var i=0; i < numSuggestValue; i++)
		{
			if(tagstmp[i].id == value)
			{
				index = i;
				break;
			}
		}
		
		if((jQuery.inArray(value,inserted) == -1) && ( index > -1 || allowNewTags)){
			var addValue = tagstmp[index];
			//delete from tags
			if(index >-1){
				tagstmp.splice(index,1);
			}
			inserted.push(value);
			tagField.parent('.superblyTagInputItem').before("<li class='superblyTagItem'><span>" + addValue.name + "</span><a><img alt='' src='/images/x.gif' /></a><input type='hidden' class='superblyTagItemHddId' value='" + value + "' /></li>");
			tagField.siblings('.superblyTagInput').val("");
			currentValue = null;
			currentItem = null;
			// add remove clicke event 
			var new_index = tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children('.superblyTagItem').size()-1;
			$(tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children('.superblyTagItem')[new_index]).children('a').click(function(e){
				//var value = $($(this).parent('.superblyTagItem').children('span')[0]).text();
				var value = $($(this).parent('.superblyTagItem').children('.superblyTagItemHddId')).val();
				removeItem(value);
			});
			$(tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children('.superblyTagItem')[new_index]).children('a').hover(function(e){
				$(this).addClass('hover');
			},function(e){
				$(this).removeClass('hover');
			});
		}
		tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').css('display', 'none').removeClass('sugperblySuggestItems-Scroll');
		//tagField.siblings('.superblyTagInput').focus();
		setValue();
		
		if(typeof(addCallBack) == 'function')
		{
			if(isCallAddCallBack)
			{
				addCallBack(value);
			}
		}		
	}
		
	function removeItem(value){
		//var index = jQuery.inArray(value,tags);
		var index = -1;
		var numSuggestValue = tags.length;
		for(var i=0; i < numSuggestValue; i++)
		{
			if(tags[i].id == value)
			{
				index = i;
				break;
			}
		}
		//var tmpIndex = jQuery.inArray(value,tagstmp);
		var tmpIndex = -1;
		var numTmpSuggestValue = tagstmp.length;
		for(var i=0; i < numTmpSuggestValue; i++)
		{
			if(tagstmp[i].id == value)
			{
				tmpIndex = i;
				break;
			}
		}	
		
		if(index > -1 && tmpIndex == -1){
			//tagstmp.push(value);
			tagstmp.push(tags[index]);
		}
		//console.info(inserted);
		index = jQuery.inArray(value,inserted);
		//console.info(value);
		//console.info(index);
		if(index > -1){
			inserted.splice(index,1);
			//tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children(".superblyTagItem:contains('" + value + "')").remove();
			
			var arrSelectedTag = tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children(".superblyTagItem");
			var numSelectedTag = arrSelectedTag.length;
			for(var i=0; i<numSelectedTag; i++)
			{
				if($(arrSelectedTag[i]).children('.superblyTagItemHddId').val() == value)
				{
					$(arrSelectedTag[i]).remove();
					break;
				}
			}
			//console.info(tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children(".superblyTagItem .superblyTagItemHddId:contains('" + value + "')"));
			
			//tagField.parent('.superblyTagInputItem').parent('.superblyTagItems').children(".superblyTagItem").children(".superblyTagItemHddId")[0].parent().remove();
		}
		//if($.browser.mozilla)
		//{
			/*
			tagstmp.sort(function(a,b) {
				var m = a.name.toLocaleString();
				var p = b.name.toLocaleString();
				var tmp = new Array(m,p);
				if(tmp[0] == m) return 1;
				if(tmp[0] == p) return -1;
				return 0;
			});
			*/
		//}
		//else
		//{
		//	tagstmp.sort();
		//}
		var tmpStore = new Array();
		numTmpSuggestValue = tagstmp.length;
		for(var i = 0; i < numSuggestValue; i++)
		{
			for(var j =0 ; j < numTmpSuggestValue; j++)
			{
				if(tags[i].id == tagstmp[j].id)
				{
					tmpStore.push(tags[i]);
					break;
				}
			}
		}
		
		tagstmp = tmpStore;
		tagField.siblings('.superblyTagInput').focus();
		setValue();
		
		if(typeof(removeCallBack) == 'function')
		{
			removeCallBack(value);
		}
	}
	
	
	
	function removeLastItem(){
    	var last_index = inserted.length-1;
    	var last_value = inserted[last_index];
    	removeItem(last_value);
	}
	
	function getSuggestionsArray(value){
		var suggestions = new Array();
    	var count = 0;
    	value = $.trim(value);
    	if(value != '')
    	{
	    	if(isFixData)
	    	{
				for(key in tagstmp){
		        	/*
					if(showTagsNumber <= count){
		        		break;
		        	}
		        	*/
					// if beginning is same
					var selectedIndex = jQuery.inArray(tagstmp[key].id, inserted);
					var lower_case_tag = tagstmp[key].name.toLocaleLowerCase();
					var lower_cast_value = value.toLowerCase();
					
					var lower_case_tag_en = removeVietChars(lower_case_tag);
					//lower_case_tag_en= lower_case_tag_en.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g," ");
					//console.info(lower_case_tag_en);
					var lower_cast_value_en = removeVietChars(lower_cast_value);
					//lower_cast_value_en= lower_cast_value_en.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g," ");
					//console.info(lower_cast_value_en);
					if((lower_case_tag_en.indexOf(lower_cast_value_en) == 0 || lower_case_tag.indexOf(lower_cast_value) == 0 )&& selectedIndex == -1){
						suggestions.push(tagstmp[key]);
						count++;
					}
				}
			}
			else
			{
				var currSelectedVal = $(tagField).val();
				for(key in tags)
				{
		        	/*
					if(showTagsNumber <= count){
		        		break;
		        	}
		        	*/
					// if beginning is same
					var selectedIndex = jQuery.inArray(tagstmp[key].id, inserted);
					var currSelectedIndex = currSelectedVal.indexOf(tagstmp[key].id);
					var lower_case_tag = tagstmp[key].name.toLocaleLowerCase();
					var lower_cast_value = value.toLowerCase();
					var lower_case_tag_en = removeVietChars(lower_case_tag);
					var lower_cast_value_en = removeVietChars(lower_cast_value);
					if((lower_case_tag_en.indexOf(lower_cast_value_en) == 0 || lower_case_tag.indexOf(lower_cast_value) == 0 )&& selectedIndex == -1 && currSelectedIndex == -1){
						suggestions.push(tagstmp[key]);
						count++;
					}
				}
			}
		}
		return suggestions;
	}
	
	
	
	function removeHtmlTag(str)
	{
		if(str == '' || str == null) return str;
		return str.replace(/<\/?[^>]+>/gi, '');
	}
	
	function suggest(value){
		var divOuter = $(tagField.siblings('.superblyTagInput').parent('.superblyTagInputItem').parent('.superblyTagItems').parent('.superblyTagfieldDiv'));
		//console.info(divOuter);
		//console.info($(divOuter));
		var divSuggestTagPos = $(divOuter).position();
		//console.info(divSuggestTagPos);
		var lPos = divSuggestTagPos.left;
		var tPos = divSuggestTagPos.top + $(divOuter).height();
		tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').css({top: tPos + 'px', left: lPos + 'px'}).addClass('sugperblySuggestItems-Scroll');
		//console.info($(tagField.siblings('.superblyTagInput').parent('.superblyTagInputItem').parent('.superblyTagItems').parent('.superblyTagfieldDiv')));
		tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').show();
		if(value == currentValue){
			return false;
		}
		currentValue = value;
		
		tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem').remove();
		var suggestions = getSuggestionsArray(value);
		//console.info(suggestions);
		for(key in suggestions)
		{	
			tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').append("<li class='superblySuggestItem'>" + hightlight(value, suggestions[key].name) + "<input type='hidden' value='" + suggestions[key].id + "' class='superblySuggestItemHddId' /></li>");
		}
		
		// add click event to suggest items
		tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem').click(function(e){
			var id = $(this).children('.superblySuggestItemHddId').val();
			addItem(id);
		});
		
		selectedIndex=null;
		if(!allowNewTags){
			selectedIndex=0;
			$(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).addClass("selected");	
			var id = $(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).children('.superblySuggestItemHddId').val();
			currentItem = id;
		}
		tagField.siblings('.superblyTagInput').parent('.superblyTagInputItem').parent('.superblyTagItems').parent('.superblyTagfieldDiv').children('.superblyTagfieldLoading').hide();
	}
	
	
	function selectDown(){
		var size = tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem').size();
		if(selectedIndex == null){
			selectedIndex=0;
		}else if(selectedIndex < size-1){
			$(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).removeClass("selected");
			selectedIndex++;
		}
		$(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).addClass("selected");
		var id = $(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).children('.superblySuggestItemHddId').val();
		currentItem = id;

	}
	
	function selectUp(){
		if(selectedIndex == 0){
			selectedIndex=null;
			currentItem = null;
			tagField.siblings('.superblyTagInput').focus();
		} else if(selectedIndex >0){
			$(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).removeClass("selected");
			selectedIndex--;
			$(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).addClass("selected");
			var id = $(tagField.siblings('.superblyTagInput').siblings('.superblySuggestItems').children('.superblySuggestItem')[selectedIndex]).children('.superblySuggestItemHddId').val();
			currentItem = id;
		}
	}	
}
